﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WeChatDouble
{
    public partial class SettingWindows : Form
    {
        /// <summary>
        /// 微信安装路径
        /// </summary>
        private string WeChatPath { get; set; }
        /// <summary>
        /// 微信启动文件路径
        /// </summary>
        private string WeChatStartPath { get; set; }
        /// <summary>
        /// 是否已经安装微信
        /// </summary>
        private bool IsInstallWeChat { get; set; } = false;
        /// <summary>
        /// 启动数量
        /// </summary>
        private int StartNum { get; set; }

        /// <summary>
        /// 进程名（用于检测进程是否存在）
        /// </summary>
        private string WeChatName { get; set; } = "WeChat";

        public SettingWindows()
        {
            InitializeComponent();
            ReadRegistry();
        }

        #region 事件
        /// <summary>
        /// 确定按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void confirm_Click(object sender, EventArgs e)
        {
            try
            {
                if (!IsInstallWeChat)
                {
                    MessageBox.Show("未检测到安装微信，请先安装微信！", "提示");
                    return;
                }
                if (Common.IsAfterStart(WeChatName))
                {
                    DialogResult dr = MessageBox.Show("检测到您已启动微信，需要关闭后才能多开，是否关闭所有微信？", "提示", MessageBoxButtons.OKCancel);
                    if (dr == DialogResult.OK)
                    {
                        Common.KillProcess(WeChatName);
                    }
                    else if (dr == DialogResult.Cancel)
                    {
                        this.Close();
                        return;
                    }
                }

                GetStartNum();
                Start();
                if (this.checkBox1.Checked) FoundLnk();
                if (this.checkBox2.Checked) SetStartup(true); else SetStartup(false);
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("多开异常：" + ex.Message);
            }
        }
        /// <summary>
        /// 输入框值改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textcount_TextChanged(object sender, EventArgs e)
        {
            if (new Regex("^[1-9]*$").IsMatch(textcount.Text.Trim()) && textcount.Text.Trim().Length > 0)
            {
                DoubleButton.Checked = false;
                ThreeButton.Checked = false;
            }
            else
            {
                DoubleButton.Checked = true;
                ThreeButton.Checked = false;
                textcount.Text = "";
            }
        }
        #endregion

        #region  方法
        /// <summary>
        /// 读取注册表检测是否安装微信,获取微信启动程序路径
        /// </summary>
        /// <returns></returns>
        private void ReadRegistry()
        {
            //D:\Install Software\WeiChatBeta\WeChat\WeChat.exe
            //计算机\HKEY_CURRENT_USER\Software\Tencent\Weixin (新版)
            WeChatPath = Common.ReadRegistry("InstallPath", @"SOFTWARE\Tencent\WeChat");
            if (!string.IsNullOrEmpty(WeChatPath))
            {
                WeChatStartPath = WeChatPath + @"\WeChat.exe";
                IsInstallWeChat = true;
            }
            else
            {
                WeChatPath = Common.ReadRegistry("InstallPath", @"SOFTWARE\Tencent\Weixin");
                WeChatStartPath = WeChatPath + @"\Weixin.exe";
                WeChatName = "Weixin";
                IsInstallWeChat = true;
            }
        }
        /// <summary>
        /// 获取启动数量
        /// </summary>
        private void GetStartNum()
        {
            if (textcount.Text.Trim().Length > 0)
            {
                StartNum = int.Parse(textcount.Text.Trim());
            }
            else
            {
                StartNum = DoubleButton.Checked ? 2 : 3;
            }
        }

        /// <summary>
        /// 启动
        /// </summary>
        private void Start()
        {
            for (int i = 0; i < StartNum; i++)
            {
                System.Diagnostics.Process.Start(WeChatStartPath);
            }
        }
        /// <summary>
        /// 创建快捷方式
        /// </summary>
        private void FoundLnk()
        {
            // 桌面路径
            string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            // 快捷方式路径
            string shortcutPath = Path.Combine(desktopPath, $"微信多开[{StartNum}].lnk");
            if (Common.IsFileExist(shortcutPath)) return;//已存在，无需创建

            string AssemblyName = Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetExecutingAssembly().Location) + $".exe";
            string AssemblyPath = Application.StartupPath + AssemblyName;

            Common.CreateShortcut(shortcutPath, AssemblyPath, "微信多开", Application.StartupPath);
        }

        /// <summary>
        /// 开机自启
        /// </summary>
        private void SetStartup(bool isStartup)
        {
            // 启动文件夹路径（开机自启）
            string startupPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
            string shortcutInStartup = Path.Combine(startupPath, $"微信多开[{StartNum}].lnk");

            try
            {
                if (!Common.IsFileExist(shortcutInStartup) && isStartup)
                {
                    string AssemblyName = Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetExecutingAssembly().Location) + $".exe";
                    string AssemblyPath = Application.StartupPath + AssemblyName;
                    Common.CreateShortcut(shortcutInStartup, AssemblyPath, "微信多开", Application.StartupPath);
                }
                else if (Common.IsFileExist(shortcutInStartup) && !isStartup)
                {
                    if (File.Exists(shortcutInStartup))
                    {
                        File.Delete(shortcutInStartup);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"无法添加开机启动：{ex.Message}", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                // 失败也不中断，只是提示
            }

        }
        #endregion
    }
}
